package com.yenlien.traceyun.business.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.business.dao.ScanRecordDao;
import com.yenlien.traceyun.business.entity.ScanRecord;
import com.yenlien.traceyun.business.service.rest.usercenter.CompanyRestService;
import com.yenlien.traceyun.common.utils.ToolsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: bigwangy@sina.com
 * @create: 2020-12-30
 * @description:
 **/

@Service
public class ScanRecordService {

    @Autowired
    private ScanRecordDao scanRecordDao;

    @Autowired
    private CompanyRestService companyRestService;

    /**
     * 保存记录
     *
     * @param request
     * @param code
     */
    public void save(HttpServletRequest request, String code) {
        ScanRecord scanRecord = new ScanRecord();
        scanRecord.setCode(code);
        scanRecord.setCreatetime(new Date());
        scanRecord.setAddress(ToolsUtil.parseIp(ToolsUtil.getIpAddr(request)));
        scanRecordDao.save(scanRecord);

    }

    public List<ScanRecord> findByCodeAndCompanyId(String code, String companyId){
        return scanRecordDao.findByCodeAndCompanyId(code, companyId);
    }

    /**
     * 保存记录
     *
     * @param request
     * @param code
     */
    public void save(HttpServletRequest request, String code, String companyId) {
        ScanRecord scanRecord = new ScanRecord();
        scanRecord.setCode(code);
        scanRecord.setCreatetime(new Date());
        scanRecord.setCompanyId(companyId);
        scanRecord.setAddress(ToolsUtil.parseIp(ToolsUtil.getIpAddr(request)));
        scanRecordDao.save(scanRecord);
    }

    /**
     * 查询
     *
     * @param code
     * @return
     */
    public JSONObject list(String code) {
        List<ScanRecord> recordList = scanRecordDao.findByCode(code, Sort.by(Sort.Direction.DESC, "createtime"));
        Map<String, List<ScanRecord>> group = recordList.stream().collect(Collectors.groupingBy(ScanRecord::getAddress));
        Map<String, Object> sanRecord = new HashMap<>();
        for (String key : group.keySet()) {
            sanRecord.put(key, group.get(key).size());
        }
        JSONObject jsonObject = new JSONObject();
        // 按地区分组后的扫码记录
        jsonObject.put("sanRecord", sanRecord);
        int size = recordList.size();
        // 总扫码次数
        jsonObject.put("total", size);
        // 首次扫码地点
        jsonObject.put("first", recordList.get(size - 1).getAddress());
        // 首次扫码时间
        jsonObject.put("firstTime", recordList.get(size - 1).getCreatetime());
        return jsonObject;
    }

    /**
     * 查询12个月每个月赋码量
     *
     * @param companyId
     * @return
     */
    public Object uniqueId(String companyId) {
        JSONObject jsonObject = (JSONObject) companyRestService.getchild(companyId);
        JSONArray companies = jsonObject.getJSONArray("data");
        List<String> getchild = new ArrayList<>();
        for (int i = 0; i < companies.size(); i++) {
            getchild.add(i, String.valueOf(companies.getJSONObject(i).get("id")));
        }
        Date date = new Date();
        Calendar ca = Calendar.getInstance();
        ca.setTime(date);
        Integer month = ca.get(Calendar.MONTH) + 1;
        Integer year = ca.get(Calendar.YEAR);
        String dateStr = year.toString() + "-" + month.toString() + "-01";
        List<Integer> arr = new ArrayList<>();
        try {
            Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);    //当前月
            List<ScanRecord> byProfessionAndCreatetimeBetween1 = scanRecordDao.findByCreatetimeBetweenAndCompanyIdIn(startDate, date, getchild);
            if (!StringUtils.isEmpty(byProfessionAndCreatetimeBetween1)) {
                arr.add(0, byProfessionAndCreatetimeBetween1.size());
            } else {
                arr.add(0, 0);
            }
            Calendar ca1 = Calendar.getInstance();
            ca1.setTime(startDate);
            for (int i = 1; i < 12; i++) {
                Date ca1Time = ca1.getTime();
                ca1.add(Calendar.MONTH, -1);
                List<ScanRecord> byProfessionAndCreatetimeBetween = scanRecordDao.findByCreatetimeBetweenAndCompanyIdIn(ca1.getTime(), ca1Time, getchild);
                if (byProfessionAndCreatetimeBetween.size() != 0) {
                    arr.add(i, byProfessionAndCreatetimeBetween1.size());
                } else {
                    arr.add(i, 0);
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return arr;
    }

    public Object distribution(String companyId) {
        JSONObject jsonObject = (JSONObject) companyRestService.getchild(companyId);
        JSONArray companies = jsonObject.getJSONArray("data");
        List<String> id = new ArrayList<>();             //查询所有市
        for (int i = 0; i < companies.size(); i++) {
            id.addAll(scanRecordDao.findAddress(companies.getJSONObject(i).getString("id")));
        }
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < id.size(); i++) {
            String address = id.get(i);
            List<ScanRecord> byAddress = scanRecordDao.findByAddress(address);
            if (!address.contains("未知")) {
                if(address.length() >= 3){
                    String add = address.substring(0, 3);
                    map.put(add, byAddress.size());
                }else if(address.length() >= 2){
                    String add = address.substring(0, 2);
                    map.put(add, byAddress.size());
                }
//                else {
//                    map.put(address, byAddress.size());
//                }
            }
        }
        return map;
    }

    public Object omit(String companyId, List<String> omit) {
        JSONObject jsonObject = (JSONObject) companyRestService.getchild(companyId);
        JSONArray companies = jsonObject.getJSONArray("data");
        Map<String, Integer> map = new HashMap<>();
        for (String s : omit) {
            String arrdess = "%" + s + "%";
            for (int i = 0; i < companies.size(); i++) {
                List<ScanRecord> ids = new ArrayList<>();             //查询所有
                ids.addAll(scanRecordDao.findByCompanyIdAndAddressLike(companies.getJSONObject(i).getString("id"), arrdess));
                map.put(s, ids.size());
            }
        }
        return map;
    }

    //扫码数量统计
    public int scanCode(String companyId) {
        return scanRecordDao.scanCode(companyId);
    }

    //扫码分布统计
    public Map scanCodeAddress(String companyId) {
        List<Map<String, Object>> list = scanRecordDao.scanAddress(companyId);
        JSONObject result = new JSONObject();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = list.get(i);
            String address = map.get("address").toString();
            if (address.equals("未知")) {
                continue;
            }
//            String addressStr = address.substring(3, address.lastIndexOf("|None|CHINANET|0|0"));
//            if (addressStr.contains("|")){
//                String[] split = addressStr.split("\\|");
//                String strAddress = split[0];
//                if ( StringUtils.isEmpty(result.get("addressStr"))) {
//                    int count = scanRecordDao.scanAddressSum(strAddress);
//                    result.put(strAddress, count);
//                }
//            }
            int count = scanRecordDao.scanAddressSum(address);
            result.put(address, count);
        }
        return result;
    }

    public static void main(String[] args) {
        String str = "CN|四川|广汉|None|CHINANET|0|0";
        String substring = str.substring(3, str.lastIndexOf("|None|CHINANET|0|0"));
        String[] split = substring.split("\\|");
        String str2 = split[0];
        System.out.println(str2);
    }

}
